<?php include 'assets/tool/01_function.php'; ?>
<?php
class LinksController extends AdminController
{
/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array("index","list","listdetail","edit","delete","save","UploadImage"),
			    "users" => array("@"),
				"expression" => "Yii::app()->user->authority == Account::ADMIN"
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			)
		);
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->render("index");
	}
	
	public function actionList()
	{
		$this->renderPartial("list");
	}
	
	public function actionListdetail()
	{
		//$dataProvider=new CActiveDataProvider('Index');
		$i_amountPerPage	= $_REQUEST["amountPerPage"];
		$i_page				= $_REQUEST["page"];
		$s_filter 			= $_REQUEST["txt_filter"];
		$s_columnName 		= $_REQUEST["columnName"];
		$s_sortMethod 		= $_REQUEST["sortMethod"];
		
		//prepare where statement
		//art.`title` LIKE '%".$s_filter."%' OR
		//art.`description` LIKE '%".$s_filter."%' 
		$s_where = "1=1";
		//prepare order statement
		$s_order = "`".$s_columnName."` ".$s_sortMethod;
		
		$i_total = Yii::app()->db->createCommand("Select Count(*) from `links` where ".$s_where.";")->queryScalar();;
		
		$arr_model = $this->getAllList($i_page, $i_amountPerPage, $s_order, $s_where);
		
		$this->renderPartial(
			"listdetail",
			array(
				"arr_data"			=> $arr_model,
				"i_totalItem"		=> $i_total,
				"i_amountPerPage"	=> $i_amountPerPage,
				"i_currentPage"		=> $i_page
			)
		);
	}
	
	public function actionEdit()
	{		
		if(isset($_POST["i_key"]) && $_POST["i_key"] > 0)
		{
			$model=$this->loadModel($_POST["i_key"]);

			$this->renderPartial(
				"edit",
				array(
					"o_model"=>$model,
					"i_key"=>$_POST["i_key"]
				)
			);
		}
		else 
			$this->renderPartial(
				"edit",
				array(
					"i_key"=>0
				)
			);
	}
	
	public function actionSave()
	{
		$date_insert = new DateTime();
		
		$m_model=new Links();
		$m_model->unsetAttributes();
		
		$m_model->identification = $_REQUEST["item_key"];
		$m_model->url = $_REQUEST["txt_url"];
		$m_model->title = $_REQUEST["txt_title"];
		$m_model->tooltip = $_REQUEST["txt_tooltip"];
		
		
		//Add record
		if( $_REQUEST["item_key"] == 0)
		{
			 $i_maxID = Yii::app()->db->createCommand()->select("max(identification) as max")->from("links")->queryScalar();
			 
			$m_model->identification = $i_maxID + 1;
			$m_model->insert = $date_insert->format("Y-m-d");
			$m_model->setIsNewRecord(true);
			if(!$m_model->save())
			{
				$arr_result = array("error" => json_encode($m_model->getErrors()));
    			exit(json_encode($arr_result));
			}
			else
			{
				$arr_result = array("result" => "Đã thêm thành công");
				exit(json_encode($arr_result));
			}
		}//End if add record
		//Update record
		else
		{
			$m_model->setIsNewRecord(false);
			if(!$m_model->save())
			{
				$arr_result = array("error" => json_encode($m_model->getErrors()));
    			exit(json_encode($arr_result));
			}
			else
			{
				$m_model->key = $_REQUEST["item_key"];
				exit(json_encode($m_model->getAttributes(array("key","url","title","tooltip","insert"))));
			}
		}//End else
		Yii::app()->end();
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		//$this->loadModel($id)->delete();
		$arr_deleteId 	= $_REQUEST["arr_deleteId"];
    	
    	if(is_array($arr_deleteId) == true) {
    	
    		$s_where		= "";
    		
    		foreach ($arr_deleteId as $value) {
    			$s_where .= "`identification` = ".$value["value"]." OR ";
    		}
    	
    		$s_where	= substr($s_where, 0, -3);
    		
			$command = Yii::app()->db->createCommand("CALL links_05_delete (:in_where)");  
			$command->bindValue("in_where",$s_where);
			$s_result = $command->execute(); 
    		
    		if( $s_result >= 0) {
    			
    			$arr_result = array("result" => $s_result);
    			exit(json_encode($arr_result));
    		}
    		else {
    			
    			$arr_error = array("error" => "Đã có lỗi với quá trình xoá, xin hãy nhấn F5 để thử lại:".$s_result);
    			exit(json_encode($arr_error));
    		}
    	
    	} else {
    		
    		$arr_error = array("error" => "Bạn phải chọn một dòng để xoá.");
    		exit(json_encode($arr_error));
    	}
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Account the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Links::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	protected function getAllList($i_page,$i_amountPerPage,$s_order,$s_where) {
		$dataProvider = new CActiveDataProvider(
			"Links",
			array(
				"criteria"=>array(
					"condition"=> $s_where,
					"order"=>$s_order
				),//End array criticle
				"pagination"=>array(
					"pageSize"=>20
				)//End array pagination
			)//End array
		);
				
		return $dataProvider->data;
	}
}